<?php
/**
 * 描述
 * Created by Paco
 * Date: 2018/10/7 Time: 14:59
 */

namespace App\Repositories\System;


use App\Models\System\Config;
use App\Repositories\Repository;

class ConfigRepository extends Repository
{
    /**
     *
     * 根据key值获取配置信息
     * @author Paco
     * @createTime 2018/6/13 11:56
     * @param $key_name
     * @param string $prifix
     * @return array|mixed
     */
    function config($name, $prifix = '')
    {
        $data = [];
        $config = Config::query()->where('name', $name)
            ->when($prifix, function ($query) use ($prifix) {
                $query->where('prefix', $prifix);
            })->first();
        if ($config) {
            $data = json_decode($config->value);
        }
        return $data;
    }

    /**
     *
     * 获取配置信息列表
     * @author Paco
     * @createTime 2018/6/13 12:00
     * @param int $page
     * @param int $page_size
     * @return mixed
     */
    function configs()
    {
        $configs = Config::query()->paginate($this->page_size, ['*'], 'page', $this->page);
        foreach ($configs as $k => $config) {
            $configs[$k]->value = json_decode($config->value, true);
        }
        return $configs;
    }

    /**
     *
     * 添加配置信息
     * @author Paco
     * @createTime 2018/6/13 14:25
     * @param $params
     * @return mixed
     */
    function addConfig($data)
    {
        $data['value'] = json_encode($data['value']);
        try {
            Config::query()->create($data);
            $this->log_done('添加系统配置', $data);
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10110);
        }
    }

    /**
     *
     * 更新配置信息
     * @author Paco
     * @createTime 2018/6/13 14:47
     * @param $id
     * @param $data
     * @return mixed
     */
    function saveConfig($id, $data)
    {
        $data['value'] = json_encode($data['value']);
        try {
            $config = Config::query()->find($id);
            if(!$config){
                return $this->respondError(10109);
            }
            $key = 'config_' . $config->prefix . '_' . $config->name;
            app('phpredis')->del($key);
            $config->fill($data);
            $config->save();
            $this->log_done('更新系统配置', $data);
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10108);
        }
    }

}